var config = require('./config.js')
var crypto = require('@/utils/encrypt/requestAes/myAesCrypto.js')

// 是否开启ASE加密
var encryptStatus = false
// 请求时间
var requestTimeout = 50000

const baseUrl = config.default.baseUrl

// 拦截返回值
function requestStop(data) {
	// 拦截token过期
	if (data.code == 401) {
		uni.showToast({
			title: data.msg,
			icon: 'none',
			duration: 2000
		});
		setTimeout(function() {
			uni.reLaunch({
				url: '/pages/login/login'
			});
		}, 1000)

		return false
	}

	// 监听非200并返回
	if (data.code != 200 && data.code != 409) {
		uni.showToast({
			title: data.msg,
			icon: 'none',
            duration: 2500
		});
	}

	return true
}

// post请求封装 可以传入methodType类型PUT
function autoRequest(url, data, methodType = "POST", isToken = true) {
	var promise = new Promise((resolve, reject) => {
		uni.request({
			url: baseUrl + url,
			data: encryptStatus ? crypto.aes.en(JSON.stringify(data)) : data,
			method: methodType,
			timeout: requestTimeout,
			// method: 'POST',
			dataType: 'json',
			header: {
				// 'content-type': 'application/x-www-form-urlencoded',
				// 'content-type': 'application/json',
				// 'content-type': 'application/text',
				'token': isToken ? uni.getStorageSync('token') : ''
			},
			success: function(res) {
				if (res) {
					if (res.header.token) {
						var userInfos = uni.getStorageSync('userInfos');
						userInfos.token = res.header.token;
						uni.setStorageSync('userInfos', userInfos);
					}
					switch (res.statusCode) {
						case 404:
							resolve('404，请求的资源不存在');
							break;
						case 500:
							resolve('500，内部服务器错误');
							break;
						default:
							// requestStop(res.data)
							if (requestStop(res.data)) resolve(res.data);
					}
				}
			},
			fail: function(e) {
				reject('网络错误！');

				console.log(e, '网络错误');

				uni.showToast({
					title: '网络错误',
					// title: e.errMsg,
					icon: 'none'
				});
			}
		})
	});
	return promise;
}

// get请求封装
function getRequest(url, data, isToken = true) {
	var promise = new Promise((resolve, reject) => {
		var postData = data;
		uni.request({
			url: baseUrl + url,
			data: postData,
			method: 'GET',
			timeout: requestTimeout,
			header: {
				// 'content-type': 'application/json',
				'token': isToken ? uni.getStorageSync('token') : ''
			},
			success: function(res) {
				if (res) {
					if (res.header.token) {
						var userInfos = uni.getStorageSync('userInfos');
						userInfos.token = res.header.token;
						uni.setStorageSync('userInfos', userInfos);
					}
					switch (res.statusCode) {
						case 404:
							resolve('404，请求的资源不存在');
							break;
						case 500:
							resolve('500，内部服务器错误');
							break;
						default:
							if (requestStop(res.data)) resolve(res.data);
					}
				}
			},
			fail: function(e) {
				reject('网络错误！');

				console.log(e, '网络错误');

				uni.showToast({
					title: e.errMsg,
					icon: 'none'
				});
			}
		})
	});
	return promise;
}


module.exports = {
	autoRequest,
	getRequest
}
